package cn.wolfcode.wolf2w.resolver;

import cn.wolfcode.wolf2w.annotation.UserParam;
import cn.wolfcode.wolf2w.cache.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.domain.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 用于解析请求映射方法中的当前登录用户的对象
 */
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private IUserInfoRedisService userInfoRedisService;


    //这个方法指定该参数解析器要解析哪个类型的参数,
    // 比如现在我要解析 UserInfo 用户信息对象
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType() == UserInfo.class
                && methodParameter.hasParameterAnnotation(UserParam.class);
    }

    //执行解析逻辑,并注入参数
    //参数解析方法,如果上边的方法返回true,表示当前处理方法需要的参数是 UserInfo 对象
    //那么我们就返回一个给它, 至于返回什么样的 UserInfo ,看需求而定
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {

        //获取当前登录对象
        HttpServletRequest req = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String token = req.getHeader("token");



        //返回值就是请求映射方法声明形式参数什么的UserInfo对象的值
        //返回当前登录用户对象
        return userInfoRedisService.getUserByToken(token);
    }
}
